package cn.zhuama.org.controller;

import cn.zhuama.basic.exception.BusinessException;
import cn.zhuama.basic.util.BaiduAuditUtils;
import cn.zhuama.basic.util.ExcelUtils;
import cn.zhuama.org.domain.ShopAuditLog;
import cn.zhuama.org.domain.ShopDto;
import cn.zhuama.org.service.IShopAuditLogService;
import cn.zhuama.org.service.IShopService;
import cn.zhuama.org.domain.Shop;
import cn.zhuama.org.query.ShopQuery;
import cn.zhuama.basic.util.AjaxResult;
import cn.zhuama.basic.util.PageList;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/shop")
public class ShopController {

    @Autowired
    public IShopService shopService;


    /**
     * 接口：添加或修改
     * @param shop  传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Shop shop){
        try {
            if( shop.getId()!=null)
                shopService.update(shop);
            else
                shopService.add(shop);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    /**
    * 接口：删除
    * @param id
    * @return AjaxResult 响应给前端
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            shopService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
        e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return AjaxResult 响应给前端
    */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
                shopService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"批量删除失败");
        }
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    public Shop findOne(@PathVariable("id")Long id) {
        return shopService.queryOne(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<Shop> findAll(){
        return shopService.findAll();
    }


   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public PageList<Shop> queryPage(@RequestBody ShopQuery query) {
        return shopService.queryPage(query);
    }

    //商家入驻接口 //先写主体，再写细节
    @ApiOperation(value = "商家入驻",notes = "")
    @PostMapping("/settlement")
    public AjaxResult settlement(@RequestBody Shop shop){
        try {
            if(!BaiduAuditUtils.TextCensor(shop.getName())){
                throw new Exception("店铺名称不合法，请重新输入！");
            }
            if(shop.getLogo()!=null){
                throw new Exception("店铺图片审核未通过或未上传，请重新插入！");
            }
            shopService.settlement(shop);
            return new AjaxResult();
        } catch (BusinessException e){ //业务异常捕获
            return AjaxResult.me().setSuccess(false).setMessage("入驻失败!"+e.getMessage());
        } catch (Exception e) { //500
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }

    @PostMapping("/audit/reject")
    public AjaxResult reject(@RequestBody ShopAuditLog log){
        try {
            shopService.reject(log);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false);
        }

    }

    @PostMapping("/audit/pass")
    public AjaxResult pass(@RequestBody ShopAuditLog log){
        try {
            shopService.pass(log);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false);
        }
    }
    @GetMapping("/active/{shopId}")
    public AjaxResult active(@PathVariable("shopId") Long id, HttpServletResponse response){
        try {
            if(shopService.run(id)){
                response.sendRedirect("Http://localhost:8081/#/lo+99999896+96+96+96+96+96+96+96+96+96+96+" +
                        "" +
                        "" +
                        "555gin");
            };
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false);
        }
    }

    @GetMapping("/export")
    public void export( HttpServletResponse response){
        try {
            List<Shop> shops = shopService.findAll();
            ExcelUtils.exportExcel(shops, null, "店铺信息", Shop.class, "shop.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/importExcel")
    public void importExcel(@RequestPart("file") MultipartFile file){
        //String file = "F:\\文件名.xls";
        //解析excel，
        List<Shop> list = ExcelUtils.importExcel(file,0,1,Shop.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
        System.out.println("导入数据一共【"+list.size()+"】行");
        for (Shop shop:list) {
            System.out.println(shop);
        }
        //保存到数据库中[自己实现，提示：动态sql 批量插入]
    }

    @GetMapping("/echarts")
    public List<ShopDto> echartsData(){
        List<ShopDto> shopDtos = shopService.getCountByState();
        return shopDtos;
    }
}
